package com.zerox.springsecuritydemo329.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zerox.springsecuritydemo329.mapper.SysUserMapper;
import com.zerox.springsecuritydemo329.pojo.LoginUser;
import com.zerox.springsecuritydemo329.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 实现从数据库查登录用户
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);

        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

        if (sysUser==null){
            throw new UsernameNotFoundException("用户不存在");
        }

        // 权限信息  要从数据库里查
        List<String> perms = sysUserMapper.findPermsByUserId(sysUser.getId());

        LoginUser loginUser = new LoginUser(sysUser,perms);

        return loginUser;
    }
}
